// app.js
const WxMqtt = require('./utils/wxmqtt.js')

App({
  globalData: {
    // MQTT配置
    mqttConfig: {
      host: '218.244.140.203', // 自定义服务器地址
      port: 8083, // WebSocket 端口（EMQX 默认 8083）
      ssl: false, // 是否使用 WSS
      path: '/mqtt', // WebSocket 路径
      subscribeTopic: 'McuToClient',    // 订阅主题（接收网关数据）
      publishTopic: 'qtmqtt/topic1'     // 发布主题（发送控制命令）
    },
    // 设备数据
    deviceData: {
      temperature: 0,
      humidity: 0,
      foodAmount: 0,
      als: 0,  // 环境光数据
      deviceFd: '',  // 设备fd
      tempThresholdMax: 30,
      tempThresholdMin: 10,
      humidThresholdMax: 60,
      humidThresholdMin: 30,
      isFoodDispensing: false,
      lastUpdate: null
    },
    // 温度历史数据（用于图表）
    temperatureHistory: [],
    // 湿度历史数据
    humidityHistory: [],
    // MQTT 连接状态
    mqttConnected: false,
    // MQTT 客户端实例
    mqttClient: null
  },

  onLaunch() {
    console.log('App launched')
    // 从本地存储加载配置
    this.loadConfig()
    // 连接 MQTT 服务器
    this.connectMQTT()
  },

  // 连接 MQTT 服务器
  connectMQTT() {
    console.log('========================================')
    console.log('🚀 开始连接 MQTT 服务器...')
    console.log('========================================')
    
    // 创建 MQTT 客户端实例
    const mqttClient = new WxMqtt()
    this.globalData.mqttClient = mqttClient
    
    // 设置事件回调
    mqttClient.on('connect', () => {
      console.log('========================================')
      console.log('✅ MQTT 连接成功！')
      console.log('========================================')
      
      this.globalData.mqttConnected = true
      
      // 订阅主题（接收网关数据）
      const subscribeTopic = this.globalData.mqttConfig.subscribeTopic
      console.log('========================================')
      console.log('📡 订阅主题（接收）:', subscribeTopic)
      console.log('📡 发布主题（发送）:', this.globalData.mqttConfig.publishTopic)
      console.log('📡 服务器地址: 218.244.140.203:8083')
      console.log('========================================')
      
      mqttClient.subscribe(subscribeTopic)
        .then(() => {
          console.log('✅ 订阅主题成功:', subscribeTopic)
          
          wx.showToast({
            title: 'MQTT已连接',
            icon: 'success',
            duration: 2000
          })
        })
        .catch((err) => {
          console.error('❌ 主题订阅失败:', err)
        })
    })
    
    mqttClient.on('message', (topic, message) => {
      console.log('========================================')
      console.log('📩 收到 MQTT 消息')
      console.log('主题:', topic)
      console.log('消息:', message)
      console.log('========================================')
      
      this.handleMQTTMessage(topic, message)
    })
    
    mqttClient.on('close', () => {
      console.log('⚠️ MQTT 连接已关闭')
      this.globalData.mqttConnected = false
    })
    
    mqttClient.on('error', (err) => {
      console.error('❌ MQTT 错误:', err)
      this.globalData.mqttConnected = false
    })
    
    // 连接服务器
    mqttClient.connect({
      host: this.globalData.mqttConfig.host,
      port: this.globalData.mqttConfig.port,
      path: this.globalData.mqttConfig.path,
      ssl: this.globalData.mqttConfig.ssl,
      keepalive: 60
    }).then(() => {
      console.log('🎉 MQTT 初始化成功')
    }).catch((err) => {
      console.error('❌ MQTT 连接失败:', err)
      this.globalData.mqttConnected = false
      
      wx.showModal({
        title: 'MQTT连接失败',
        content: `无法连接到服务器：${this.globalData.mqttConfig.host}:${this.globalData.mqttConfig.port}`,
        showCancel: false
      })
    })
  },

  // 处理 MQTT 消息
  handleMQTTMessage(topic, message) {
    try {
      // 解析 JSON 消息
      const data = JSON.parse(message)
      console.log('📊 解析后的数据:', data)
      
      // 更新设备数据
      this.receiveData(data)
    } catch (e) {
      console.error('❌ 处理 MQTT 消息失败:', e)
      console.error('原始消息:', message)
    }
  },

  // 发送 MQTT 消息
  sendMQTTMessage(data) {
    const mqttClient = this.globalData.mqttClient
    
    if (!mqttClient || !mqttClient.isConnected()) {
      console.error('❌ MQTT 未连接，无法发送消息')
      wx.showToast({
        title: 'MQTT未连接',
        icon: 'none'
      })
      return Promise.reject({ error: '未连接' })
    }
    
    // 使用发布主题发送消息
    const publishTopic = this.globalData.mqttConfig.publishTopic
    const message = JSON.stringify(data)
    
    console.log('========================================')
    console.log('📤 发送 MQTT 消息')
    console.log('发布主题:', publishTopic)
    console.log('消息内容:', message)
    console.log('========================================')
    
    return mqttClient.publish(publishTopic, message)
  },

  // 接收并处理数据
  receiveData(data) {
    const deviceData = this.globalData.deviceData
    
    console.log('接收到设备数据:', data)
    
    // 更新设备fd（接收int或string，统一保存为string）
    if (data.fd !== undefined) {
      deviceData.deviceFd = String(data.fd)  // int或string都转为string
      console.log('更新设备fd:', deviceData.deviceFd)
    }
    
    // 更新温度（统一字符串格式）
    if (data.Tem !== undefined) {
      deviceData.temperature = parseFloat(data.Tem)
      // 添加到历史记录
      const now = new Date()
      this.globalData.temperatureHistory.push({
        time: now.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        }),
        value: deviceData.temperature
      })
      // 保持历史记录最多30条
      if (this.globalData.temperatureHistory.length > 30) {
        this.globalData.temperatureHistory.shift()
      }
    }
    
    // 更新湿度（统一字符串格式）
    if (data.Hum !== undefined) {
      deviceData.humidity = parseFloat(data.Hum)
      // 添加到历史记录
      const now = new Date()
      this.globalData.humidityHistory.push({
        time: now.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        }),
        value: deviceData.humidity
      })
      // 保持历史记录最多30条
      if (this.globalData.humidityHistory.length > 30) {
        this.globalData.humidityHistory.shift()
      }
    }
    
    // 更新食物量（统一字符串格式）
    if (data.food !== undefined) {
      deviceData.foodAmount = parseInt(data.food)
    }
    
    // 更新环境光（统一字符串格式）
    if (data.ALS !== undefined) {
      deviceData.als = parseInt(data.ALS)
      console.log('更新环境光:', deviceData.als)
    }
    
    // 更新投喂状态
    if (data.is_food_dispensing !== undefined) {
      deviceData.isFoodDispensing = data.is_food_dispensing
    }
    
    deviceData.lastUpdate = new Date().toLocaleString('zh-CN')
  },

  // 加载配置
  loadConfig() {
    try {
      const config = wx.getStorageSync('mqttConfig')
      if (config) {
        this.globalData.mqttConfig = config
      }
      const thresholds = wx.getStorageSync('thresholds')
      if (thresholds) {
        Object.assign(this.globalData.deviceData, thresholds)
      }
    } catch (e) {
      console.error('加载配置失败:', e)
    }
  },

  // 保存配置
  saveConfig() {
    try {
      wx.setStorageSync('mqttConfig', this.globalData.mqttConfig)
      wx.setStorageSync('thresholds', {
        tempThresholdMax: this.globalData.deviceData.tempThresholdMax,
        tempThresholdMin: this.globalData.deviceData.tempThresholdMin,
        humidThresholdMax: this.globalData.deviceData.humidThresholdMax,
        humidThresholdMin: this.globalData.deviceData.humidThresholdMin
      })
    } catch (e) {
      console.error('保存配置失败:', e)
    }
  },


  // 获取温度状态
  getTempStatus() {
    const temp = this.globalData.deviceData.temperature
    const max = this.globalData.deviceData.tempThresholdMax
    const min = this.globalData.deviceData.tempThresholdMin
    
    if (temp >= max) {
      return { text: '温度过高', color: '#ff4d4f' }
    } else if (temp <= min) {
      return { text: '温度过低', color: '#1890ff' }
    } else {
      return { text: '温度正常', color: '#52c41a' }
    }
  },

  // 获取湿度状态
  getHumidStatus() {
    const humid = this.globalData.deviceData.humidity
    const max = this.globalData.deviceData.humidThresholdMax
    const min = this.globalData.deviceData.humidThresholdMin
    
    if (humid >= max) {
      return { text: '湿度过高', color: '#ff4d4f' }
    } else if (humid <= min) {
      return { text: '湿度过低', color: '#faad14' }
    } else {
      return { text: '湿度正常', color: '#52c41a' }
    }
  }
})

